<?php

namespace App\Service\playlet;
use App\Model\Applet;
use App\Model\AppletCompany;
use App\Service\CommicService;
use App\Model\Company;
use GuzzleHttp\Client;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class ComplaintsService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        //查询小程序的key
        $appletInfo = Applet::query()->select(['id' => 10000])->select(['id','AppKey','app_id','app_secret'])->first();
        $accessToken = env('WX_TEST_TOKEN');
        if(!empty($accessToken)){

            return $this->checkWxComplaint($appletInfo->AppKey,$accessToken);
        }



    }

    /**
     * 检查微信订单
     */
    public function checkWxComplaint($appkey,$accessToken){



        $url = '/xpay/get_complaint_list';
        $params = [
            'env'=>0,
            'begin_date' => '2023-12-01',
            'end_date' => date('Y-m-d'),
            'offset' => 0,
            'limit'=> 50

        ];
        $pay_sig = $this->get_paySig($appkey,$url,$params);
        $orderUrl = 'https://api.weixin.qq.com'.$url.'?access_token='.$accessToken.'&pay_sig='.$pay_sig;
        $orderResult  = $this->request($params,$orderUrl, 'POST');
        return $orderResult;
    }


    public function getToken($applet_id,$type){

        $container = ApplicationContext::getContainer();

        if($type == 1){
            $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

            $key = 'wx_access_token';
        }else{
            $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

            $key = 'dy_admin_access_token';
        }
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        return $accessToken;
    }


    public function getWxAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'appid'    => $app_id,
                'secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'GET');

            if (!empty($accessTokenInfo['access_token'])){
                $accessToken = $accessTokenInfo['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }
    /**
     * 生成虚拟支付的pay_sig
     */
    public function get_paySig($appkey,$url,$signData) {
        $paySig = $this->calcPaySig($url, $signData, $appkey);
        return $paySig;
    }
    /**
     * 生成虚拟支付的pay_sig
     */
    private function calcPaySig($uri, $postBody, $appkey)
    {
        $needSignMsg = $uri . '&' . json_encode($postBody);
        $paySig = hash_hmac('sha256', $needSignMsg, $appkey);
        return $paySig;
    }

    function request(array $params, string $url,string $method,string $access_token = null)
    {
        try {

            $client   = new Client([
                'timeout' => 3
            ]);
            $headers       = ['Content-Type' => 'application/json'];
            if(!empty($access_token)){
                $headers['access-token'] = $access_token;
            }

            $requestParams = [
                'headers' => $headers,
            ];
            if ($method == 'GET') {
                $requestParams['query'] = $params;
            } else {
                $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
            }
            $response = $client->request($method,$url, $requestParams);
            if ($response->getStatusCode() !== 200) {
                return '';
            }
            $result   = $response->getBody()->getContents();

            $resultArr = json_decode($result,true);
            return $resultArr;

        }catch (\Exception $e){

            $resultArr['errcode'] = '500';
            $resultArr['errmsg'] = $e->getMessage();
            return $resultArr;
        }

    }
}